<?php

class ProfileController extends Controller {

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public $defaultAction = 'profile';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * Shows a particular model.
     */
    public function accessRules() {
        return array(
            array('allow', // allow authenticated user
                'actions' => array('Updateprofile', 'Uploadphoto', 'deletephoto', 'myskillhippo', 'checkProfile', 'Changepassword'),
                'users' => array('@'),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function actionProfile() {
        $model = $this->loadUser();
        $this->render('profile', array(
            'model' => $model,
            'profile' => $model->profile,
        ));
    }

    public function actioncheckProfile() {
        $profile = Profiles::model()->findByAttributes(array('user_id' => getLoginUserId()));
        if (isset($_POST['action'])) {
            if ($profile->first_name == '') {
                echo SkillConfig::STATUS_ACTIVE;
            } else {
                echo Yii::app()->createAbsoluteUrl($_POST['action']);
            }
        }
    }

    public function actionUpdateprofile() {
        /* This is for CMS of term and condion */
        $profile = Profile::model()->findByAttributes(array('user_id' => getLoginUserId()));
        Yii::app()->getModule('cms');
        $cmsContent = CmsContent::model()->findByAttributes(array('id' => 2));
        /* This is check user valid data */
        $isCorporate = '';
        $redirectUrl = Yii::app()->createUrl('user/profile/myskillhippo/');
        $corporateprogram = (!$profile->corporateprogram) ? new CorporateProgram() : $profile->corporateprogram;
        if (isset($_POST['Profile'])) {        
            //$profile->setAttributes($_POST['Profile']);        
            $profile->setAttribute('first_name', $_POST['Profile']['first_name']);
            $profile->setAttribute('last_name', $_POST['Profile']['last_name']);
            $profile->setAttribute('phone', $_POST['Profile']['phone']);
            $profile->setAttribute('date_of_birth', $_POST['Profile']['date_of_birth']);
            $profile->setAttribute('about', $_POST['Profile']['about']);
            $profile->setAttribute('experience', $_POST['Profile']['experience']);
            $profile->setAttribute('other_info', $_POST['Profile']['other_info']);
            $profile->setAttribute('termcondition', $_POST['Profile']['termcondition']);
            $profile->setAttribute('others_link', $_POST['Profile']['others_link']);
            $profile->setAttribute('others', $_POST['Profile']['others']);
            $profile->setAttribute('blog_link', $_POST['Profile']['blog_link']);
            $profile->setAttribute('blog_title', $_POST['Profile']['blog_title']);
            $profile->setAttribute('website_title', $_POST['Profile']['website_title']);
            $profile->setAttribute('linkedin', $_POST['Profile']['linkedin']);
            $profile->setAttribute('twitter', $_POST['Profile']['twitter']);
            $profile->setAttribute('facebook', $_POST['Profile']['facebook']);
            $profile->setAttribute('privacy', 'public');            
            $valid = $profile->validate();         
            if (isset($_POST['isCorporate']) && $_POST['isCorporate'] == 1) {
                $corporateprogram->attributes = $_POST['CorporateProgram'];
                $corporateprogram->profiles_id = $profile->profile_id;
                $corporateprogram->users_id = Yii::app()->user->id;
                $valid = $corporateprogram->validate() && $valid;
                $isCorporate = $_POST['isCorporate'];
            } else {
                if (!$corporateprogram->isNewRecord) {
                    $corporateprogram->delete();
                }
            }
            if ($valid) {
                echo $valid;die;
                $transaction = Yii::app()->getDb()->beginTransaction();
                try {
                    $profile->cache_last_updated = date("Y-m-d H:i:s");
                    $subscribeValue = (isset($_POST['RegistrationForm']['issubscribe'])) ? $_POST['RegistrationForm']['issubscribe'] : '0';
                    Users::model()->updateByPk(getLoginUserId(), array('issubscribe' => $subscribeValue));
                    if ($profile->save()) {
                        $corporateprogram->save();
                    }
                    $transaction->commit();
                    $this->redirect($redirectUrl);
                } catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            }
        }
        $folder = getUploadDir() . Yii::app()->user->id . '/'; // folder for uploaded files
        $user = User::model()->findByAttributes(array('id' => Yii::app()->user->id));
        $deletePicureUrl = Yii::app()->createUrl('user/profile/deletephoto');
        $this->render('/profile/create-profile', array(
            'profile' => $profile,
            'corporateprogram' => $corporateprogram,
            'isCorporate' => $isCorporate,
            'deletePicureUrl' => $deletePicureUrl,
            'userFolder' => $folder,
            'termcondition_value' => $cmsContent->body,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionmySkillhippo() {
        $classTrainerRate = '';
        $classtotalCountTrainerate = '';
        $this->layout = 'frontend.www.themes.front-end.views.layouts.detailspage';
        $profiles = Users::getFrontEndUser(getLoginUserId());
        $class = Classes::model()->findByAttributes(array('users_id' => getLoginUserId()));
        $courses = Courses::model()->findByAttributes(array('users_id' => getLoginUserId()));
        if (!empty($courses)) {
            $classTrainerRate = Classes::trainerPossitiverate('front-end', $courses);
            $classtotalCountTrainerate = Classes::trainertotalRate('front-end', $courses);
        }
        if (!empty($class)) {
            $classTrainerRate = Classes::trainerPossitiverate('front-end', $class);
            $classtotalCountTrainerate = Classes::trainertotalRate('front-end', $class);
        }
        $this->render('/profile/myprofile', array('profiles' => $profiles, 'classTrainerRate' => $classTrainerRate, 'classtotalCountTrainerate' => $classtotalCountTrainerate,
        ));
    }


    public function actionChangepassword() {
        if (Yii::app()->user->id) {
            if (isset($_POST['password'])) {
                $new_password = User::model()->findbyPk(getLoginUserId());
                $new_password->password = md5($_POST['password']);
                if ($new_password->save()) {
                    $mailmodel = EmailTemplate::model()->findByPk(Message::RESET_PASSWORD);
                    $userText = $mailmodel->body;
                    $mailbody = array('value' => $userText, 'type' => 'raw');
                    $subject = $mailmodel->subject;
                    $userName = $new_password->username;
                    $mailto = $new_password->username;
                    $arrayFind = array('[username]');
                    $arrayReplace = array($userName);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        echo "success";
                        Yii::app()->end();
                    } catch (Exception $e) {
                        exit;
                    }
                }
                exit();
            }
        }
    }

    /**
     * Upload profile picute
     */
    public function actionUploadphoto() {
        $folder = getUploadDir(); // folder for uploaded files
        if (isset($_GET['qqfile']) && isset($_GET['id']) && !empty($_GET['qqfile']) && !empty($_GET['id'])) {
            $user = User::model()->findByAttributes(array('id' => Yii::app()->user->id));
            makeUploadDir(getLoginUserId());
        }
        $folder = $folder . getLoginUserId() . '/';
        Yii::import("common.extensions.EAjaxUpload.qqFileUploader");
        $allowedExtensions = array("jpg", "jpeg", "gif", "png", "JPG", "JPEG", "GIF", "PNG"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = SkillConfig::MAX_IMAGE_SIZE_UPLOAD; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        if ($result['success']) {
            $profile = Profile::model()->findByPk((int) $_GET['id']);
            if ($profile->photo <> "" && file_exists($folder . 'profile/' . $profile->photo) && file_exists($folder . 'profile/thumb/' . $profile->photo) && file_exists($folder . 'profile/minithumb/' . $profile->photo) && file_exists($folder . 'profile/432X324/' . $profile->photo)) {
                unlink($folder . 'profile/' . $profile->photo);
                unlink($folder . 'profile/thumb/' . $profile->photo);
                unlink($folder . 'profile/minithumb/' . $profile->photo);
                unlink($folder . 'profile/432X324/' . $profile->photo);
            }
            Profile::model()->updateByPk($_GET['id'], array(
                'cache_last_updated' => date("Y-m-d H:i:s"),
                'photo' => $result['filename']
            ));
        }

        $return = CJSON::encode($result);
        $fileSize = filesize($folder . 'profile/' . $result['filename']); //GETTING FILE SIZE
        $fileName = $result['filename']; //GETTING FILE NAME
        echo $return;
    }

    /**
     * Delete profile picute
     */
    public function actionDeletephoto() {
        $folder = getUploadDir(); // folder for uploaded files
        $folder = $folder . Yii::app()->user->id . '/';
        if (isset($_POST['delete']) && isset($_POST['profile_id']) && $_POST['profile_id'] <> "") {
            $profile = Profile::model()->findByPk((int) $_POST['profile_id']);
            if ($profile->photo <> "" && file_exists($folder . 'profile/' . $profile->photo) && file_exists($folder . 'profile/thumb/' . $profile->photo) && file_exists($folder . 'profile/minithumb/' . $profile->photo)) {
                unlink($folder . 'profile/' . $profile->photo);
                unlink($folder . 'profile/thumb/' . $profile->photo);
                unlink($folder . 'profile/minithumb/' . $profile->photo);
                unlink($folder . 'profile/432X324/' . $profile->photo);
            }
            Profile::model()->updateByPk($_GET['profile_id'], array(
                'cache_last_updated' => date("Y-m-d H:i:s"),
                'photo' => ''
            ));
            echo "deleted";
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser() {
        if ($this->_model === null) {
            if (Yii::app()->user->id)
                $this->_model = Yii::app()->controller->module->user();
            if ($this->_model === null)
                $this->redirect(Yii::app()->controller->module->loginUrl);
        }
        return $this->_model;
    }

}